package com.macro.mall.common.config;

import com.macro.mall.common.util.MDCUtil;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * 用于Feign调用时传递traceId的拦截器
 * @author macro
 */
@Component
@RequiredArgsConstructor
public class TraceIdFeignInterceptor implements RequestInterceptor {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(TraceIdFeignInterceptor.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            // 获取当前请求的属性
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                
                if (headerNames != null) {
                    // 遍历所有请求头
                    while (headerNames.hasMoreElements()) {
                        String headerName = headerNames.nextElement();
                        String headerValue = request.getHeader(headerName);
                        
                        // 传递traceId相关请求头
                        if ("traceId".equalsIgnoreCase(headerName)||"sTraceId".equalsIgnoreCase(headerName)) {
                            if ("traceId".equalsIgnoreCase(headerName)) {
                                MDCUtil.setTraceId(headerValue);
                            }
                            if ("sTraceId".equalsIgnoreCase(headerName)) {
                                MDCUtil.setSTraceId(headerValue);
                            }
                            requestTemplate.header(headerName, headerValue);
                            LOGGER.info("Feign传递请求头: {} = {}", headerName, headerValue);
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("Feign拦截器传递traceId失败", e);
        }
    }
}